﻿using ClumsyWords.DataModel;
using ClumsyWords.Portable.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Group Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234229

namespace ClumsyWords
{
    /// <summary>
    /// A page that displays an overview of a single group, including a preview of the items
    /// within the group.
    /// </summary>
    public sealed partial class GroupDetailPage : ClumsyWords.Common.LayoutAwarePage
    {
        public GroupDetailPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var group = DefinitionsDataSource.Instance.GetGroup((String)navigationParameter);
            this.DefaultViewModel["Group"] = group;
            this.DefaultViewModel["Items"] = group.Items;

            DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;

            if (group.Title == "Recent")
                this.groupSubtitleTextBlock.Text = Application.Current.Resources["RecentGroupSubtitle"].ToString();
            else
                this.groupSubtitleTextBlock.Text = Application.Current.Resources["FavouritesGroupSubtitle"].ToString();
        }

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            DataTransferManager.GetForCurrentView().DataRequested -= OnDataRequested;
        }

        #region Share Functionality Methods

        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            var group = (DefinitionsDataGroup)this.DefaultViewModel["Group"];

            request.Data.Properties.Title = String.Empty;

            string definitionsString = "<style>body{word-wrap:break-word;} h2{text-align:center;}</style>";

            if (this.itemGridView.SelectedItems.Count == 0)
            {
                foreach (var item in group.Items)
                {
                    request.Data.Properties.Title += item.Term + ", ";
                    definitionsString += GetHtmlFormattedText(item);
                }
            }

            else
            {
                CommonGroup<DefinitionsDataItem> selectedItems = new CommonGroup<DefinitionsDataItem>();
                DefinitionsDataItem currentItem;

                foreach (var selectedItem in this.itemGridView.SelectedItems)
                {
                    currentItem = (DefinitionsDataItem)selectedItem;

                    if (!selectedItems.Items.Contains(currentItem))
                        selectedItems.Items.Add(currentItem);
                }

                foreach (var item in selectedItems.Items)
                {
                    request.Data.Properties.Title += item.Term + ", ";
                    definitionsString += GetHtmlFormattedText(item);
                }
            }

            definitionsString = HtmlFormatHelper.CreateHtmlFormat(definitionsString);
            request.Data.SetHtmlFormat(definitionsString);
        }

        #endregion

        /// <summary>
        /// Invoked when an item is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((DefinitionsDataItem)e.ClickedItem).Id;
            this.Frame.Navigate(typeof(ItemDetailPage), itemId);
        }

        private void OnAddToFavouritesClick(object sender, RoutedEventArgs e)
        {
            List<object> selectedItems = this.itemGridView.SelectedItems.ToList();
            foreach (var item in selectedItems)
            {
                if (!DefinitionsDataSource.Instance.GetGroup("Favourites").ContainsSimilar((DefinitionsDataItem)item))
                {
                    DefinitionsDataSource.Instance.GetGroup("Favourites").Items.Add(new DefinitionsDataItem((DefinitionsDataItem)item));
                }
            }
            this.itemGridView.SelectedItems.Clear();
        }

        private void OnClearSelectionClick(object sender, RoutedEventArgs e)
        {
            if (this.itemGridView.SelectedItems.Count != 0)
                this.itemGridView.SelectedItems.Clear();
        }

        private void OnDeleteSelectedItemsClick(object sender, RoutedEventArgs e)
        {
            List<object> selectedItems = this.itemGridView.SelectedItems.ToList();
            foreach (var selectedItem in selectedItems)
            {
                foreach (var group in (List<DefinitionsDataGroup>)this.DefaultViewModel["Groups"])
                {
                    for (int i = group.Items.Count - 1; i >= 0; i--)
                    {
                        if (group.Items[i].Id == ((DefinitionsDataItem)selectedItem).Id)
                        {
                            group.Items.Remove(group.Items[i]);
                            break;
                        }
                    }
                }
            }
        }

        private void OnGoHomeClick(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(GroupedItemsPage), "Recent Favourites");
        }
    }
}
